package org.base.admin.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.base.admin.modules.sys.service.SysDictService;
import org.base.dao.modules.sys.model.SysDictDO;


public class DictCache {
	
	private final static Map<String,Map<String,SysDictDO>> cache = new HashMap<>();
	
	private DictCache() {}
	
	private static void init() {
		if(!cache.isEmpty()) return;
		refreshCache();
		
	}
	
	/**
	 * 此方法应在未重启应用且库表数据有更新时才被调用
	 */
	public static synchronized void refreshCache() {
		SysDictService sysDictService = SpringUtils.getBean(SysDictService.class);
		List<SysDictDO> list = sysDictService.getAll();
		Map<String,List<SysDictDO>> typeMap = list.stream().collect(Collectors.groupingBy(SysDictDO::getType));
		typeMap.entrySet().forEach(dicts -> {
			Map<String,SysDictDO> codeMap = dicts.getValue().stream().collect(Collectors.toMap(SysDictDO::getCode, Function.identity(), (key1, key2) -> key2));
			cache.put(dicts.getKey(), codeMap);
		});
	}
	
	public static List<SysDictDO> getDictByType(String type){
		init();
		Map<String,SysDictDO> typeMap = cache.get(type);
		if(Objects.isNull(typeMap))
			return new ArrayList<>(0);
		return new ArrayList<>(typeMap.values());
	}
	
	public static Map<String,String> getPairsByType(String type) {
		Collection<SysDictDO> typeList = getDictByType(type);
		Map<String,String> pairs = new HashMap<>(typeList.size());
		typeList.forEach(dict -> {
			pairs.put(dict.getCode(), dict.getValue());
		});
		return pairs;
	}
	
	public static String getValue(String type, String code) {
		return getPairsByType(type).get(code);
	}
	
	public static List<SysDictDO> getAll() {
		init();
		List<SysDictDO> dicts = new ArrayList<>();
		cache.entrySet().forEach(ds -> {
			dicts.addAll(ds.getValue().values());
		});
		return dicts;
	}
	
	public static Set<String> getAllType() {
		init();
		return new HashSet<>(cache.keySet());
	}
	
}
